package com.xingchi.tornado.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingchi.tornado.basic.Result;
import com.xingchi.tornado.core.code.SecurityCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 默认无权访问处理器
 *
 * @author xingchi
 * @date 2025/9/9 21:37
 */
@Slf4j
public class DefaultAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    public DefaultAccessDeniedHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        log.error("权限不足 {}", accessDeniedException.getMessage(), accessDeniedException);
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType("application/json; charset=utf-8");

        Result<Object> fail = Result.fail(SecurityCode.PERMISSION_DENIED);
        response.getWriter().print(objectMapper.writeValueAsString(fail));
    }
}
